<template>
  <div class="shop-index">
    <div class="shop-head">
      <div class="shop-logo">
        <div class="img">
          <img :src="this.shopInfo.shopLogo" alt />
        </div>
        <div class="text">
          <div class="name">{{ this.shopInfo.shopName }}</div>
          <div class="operation">
            <div class="self" v-if="this.shopInfo.shopId">
              {{ this.shopInfo.shopId == 1 ? $t('shopInfo.selfShop') : $t('shopInfo.preferredStores') }}
            </div>
            <div
              class="favourite"
              :class="{ active: this.isCollection }"
              @click="shopCollection()"
            >
              <i class="icon"></i>
              {{ this.isCollection ? $t('shopInfo.followed') : $t('shopInfo.follow') }}
            </div>
          </div>
        </div>
      </div>
      <div class="shop-news">
        <div class="news-tit">
          <div class="tit">{{$t('storeAnnouncement')}}</div>
          <div class="more" @click="toNewsList" v-if="noticeList.length">
            {{$t('more')}}&nbsp;&nbsp;
          </div>
        </div>
        <div class="news-list-con" v-if="noticeList.length">
          <div
            class="news-item"
            v-for="(news, index) in noticeList"
            :key="index"
            @click="toNewsDet(news.id)"
          >
            {{ news.title }}
          </div>
        </div>
        <div class="news-empty" v-else>
          {{$t('shopInfo.noAnnouncement')}}
        </div>
      </div>
    </div>
    <div class="shop-menu">
      <div class="menu-box">
        <div class="menu-list">
          <div class="menu">
            <a href="javascript:void(0);" @click="homePage" class="menu-link"
              >{{$t('shopInfo.homePage')}}</a
            >
          </div>
          <div class="menu all-category">
            <a
              href="javascript:void(0);"
              class="menu-link"
              @click="getProdListByCategory()"
              >{{$t('shopInfo.allCategories')}}</a
            >
            <div class="menu-wrap">
              <div
                class="wrap-item"
                v-for="category in this.categoryList"
                :key="category.categoryId"
                v-show='category.categoryId'
              >
                <div class="item-tit">
                  <a
                    href="javascript:void(0);"
                    @click="getProdListByCategory(category.categoryId)"
                    >{{ category.categoryName }}</a
                  >
                </div>
              </div>
              <div class='item-tit-no' v-show='this.categoryList.length===0'>{{$t('shopInfo.noData')}}</div>
            </div>
          </div>
          <div
            class="menu"
            v-for="category in categoryList"
            :key="category.categoryId"
          >
            <a
              href="javascript:void(0);"
              @click="getProdListByCategory(category.categoryId)"
              class="menu-link"
              >{{ category.categoryName }}</a
            >
          </div>
          <!-- <div class="menu">
            <a href="javascript:void(0)" class="menu-link">热卖排行</a>
          </div>
          <div class="menu">
            <a href="javascript:void(0)" class="menu-link">臻美配饰</a>
          </div>
          <div class="menu">
            <a href="javascript:void(0)" class="menu-link">绅士男表</a>
          </div>
          <div class="menu">
            <a href="javascript:void(0)" class="menu-link">优雅女表</a>
          </div>
          <div class="menu">
            <a href="javascript:void(0)" class="menu-link">表白礼物</a>
          </div>-->
        </div>
        <div class="shop-search">
          <input type="text" class="s-input" v-model="prodName" />
          <input
            type="button"
            :value="$t('shopInfo.search')"
            class="s-btn"
            @click="getSearchProdPage(1)"
          />
        </div>
      </div>
    </div>
    <!--
    <div class="shop-banner">
      <img src="~/assets/img/banner.png" alt />
    </div>-->
    <!-- banner -->
    <div class="banner" v-if="banners.length > 0">
      <el-carousel height="450px" style="overflow-y: hidden;">
        <el-carousel-item v-for="banner in banners" :key="banner.imgUrl">
          <img
            :src="banner.imgUrl"
            style="width:100%;height:100%;"
            @click="imgToProd(banner)"
          />
        </el-carousel-item>
      </el-carousel>
    </div>
    <!-- /banner -->
    <div class="content">
      <div class="shop-content">
        <div class="tit" v-if="prodList.length > 0">
          <span class="bg-l"></span>
          {{ this.categoryName ? this.categoryName : $t('shopInfo.hotProducts') }}
          <span class="bg-r"></span>
        </div>
        <div class="goods-list">
          <div class="list-con">
            <!-- 商品 -->
            <div class="item" v-for="prod in prodList" :key="prod.prodId">
              <div class="goods-img" @click="toProdDetail(prod.prodId)">
                <img :src="prod.pic" alt />
              </div>
              <div class="goods-msg" @click="toProdDetail(prod.prodId)">
                <div class="goods-name">{{ prod.prodName }}</div>
                <div class="goods-price">
                  <div class="price">
                    ￥
                    <span class="big"
                      >{{ parsePrice(prod.price)[0] }}.{{
                        parsePrice(prod.price)[1]
                      }}</span
                    >
                  </div>
                </div>
              </div>
            </div>
            <!-- 商品 -->
            <div class="empty" v-if="prodList.length < 1">
              <div class="img">
                <img src="~/assets/images/emptyPic/not-found.png" alt />
              </div>
              <div class="action">
                <div class="text">{{$t('sorryNoRelatedProducts')}}</div>
                <a :href="'/shopIndex?sid=' + shopId" class="btn">{{$t('lookAtOther')}}</a>
                <a href="/" class="btn-r">{{$t('shopInfo.mallHome')}}</a>
              </div>
            </div>
          </div>
        </div>
        <!-- 全部 -->
        <br />
        <div class="goods-list">
          <!-- 页码 -->
          <pagination
            v-model="current"
            :pages="pages"
            @changePage="getSearchProdPage"
          ></pagination>
          <!-- /页码 -->
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import PageUtil from '~/plugins/pageUtil'
import { mapState } from 'vuex'
import Pagination from '~/components/pagination'
export default {
  components: {
    Pagination
  },
  data() {
    return {
      shopId: null //店铺id
    }
  },
  /**
   * pn: 商品名称
   * cid: 店铺分类id
   * sid: 店铺id
   * sort: 根据默认(0)/销量(1)/价格(2)排序
   * size: 每页的数据数量
   * ob: 0正序 1倒序
   * c: 当前第几页
   * @param query
   */

  async asyncData({ app, query }) {
    let [prodPage, categoryList, shopInfo, banners] = await Promise.all([
      app.$axios.get(
        query.st == 4 ? '/coupon/prodListByCouponId' : '/search/searchProdPage',
        {
          //商品列表
          params: {
            sort: 0,
            size: 20,
            orderBy: parseInt(query.ob) || 0,
            current: query.c ? query.c : 1,
            shopId: query.sid,
            couponId: query.couponId || '',
            prodName: query.pn || null,
            shopCategoryId: query.cid || '',
            isAllProdType: true
          }
        }
      ),
      app.$axios.get('/category/categoryInfo', {
        //店铺商品分类
        params: {
          shopId: query.sid,
          parentId: 0
        }
      }),
      app.$axios.get('/shop/headInfo', {
        //店铺头部信息
        params: {
          shopId: query.sid
        }
      }),
      app.$axios.get('/indexImgs/' + query.sid, {
        //轮播图
        params: {
          imgType: 1
        }
      })
    ])
    return {
      prodPage: prodPage.data,
      categoryList: categoryList.data,
      shopInfo: shopInfo.data,
      banners: banners.data,
      categoryId: query.cid ? query.cid : '',
      prodName: query.pn,
      current: query.c ? query.c : 1
    }
  },
  data() {
    return {
      shopId: 0,
      categoryId: '',
      categoryName: '',
      prodName: '',
      page: {
        pages: 0, // 总页数
        rainbow: [] // 分页条
      },
      pages: 0,
      categoryList: [],
      prodList: [],
      prodPage: [],
      banners: [],
      isCollection: false,
      noticeList: []
    }
  },
  mounted() {
    document.title = this.$i18n.t('shopInfo.storeHome')
    this.getInfo()
    this.getUserCollection()
    this.getShopNews()
  },
  methods: {
    /**
     * 跳转公告详情
     */
    toNewsDet(id) {
      this.$router.push({
        path: '/notice-detail',
        query: { id: id, shopId: this.shopId }
      })
    },
    /**
     * 跳转公告列表
     */
    toNewsList() {
      this.$router.push({
        path: '/notice-list',
        query: { shopId: this.shopId }
      })
    },
    /**
     * 获取店铺公告
     */
    getShopNews() {

      if(!this.shopId){

        this.$message({

          message: this.$t('userCenter.theStoreOffline'),
          duration: 1000,
          type: 'warning'

        });

        return
      }

      this.$axios
        .get('/shop/notice/noticeList/' + this.shopId, {
          params: {
            current: 1, //当前页
            size: 2
          }
        })
        .then(({ data }) => {
          this.noticeList = data.records
        })

    },
    /**
     * 获取店铺信息
     */
    getInfo() {
      this.shopId = this.shopInfo.shopId
      this.pages = this.prodPage.pages
      this.prodList = this.prodPage.records
      this.current = this.prodPage.current
      if (this.categoryId) {
        this.categoryList.forEach(category => {
          if (this.categoryId === category.categoryId.toString()) {
            this.categoryName = category.categoryName
          }
        })
      }
    },
    /**
     * 获取用户是否收藏此店铺
     */
    getUserCollection() {
      this.$axios
        .get('/p/shop/collection/isCollection', {
          params: {
            shopId: this.shopId
          }
        })
        .then(({ data }) => {
          this.isCollection = data
        })
    },
    /**
     * 收藏店铺/取消收藏
     */
    shopCollection() {
      this.$axios
        .post('/p/shop/collection/addOrCancel', this.shopId)
        .then(({ data }) => {
          if (data) {
            this.$message({
              message: this.$t('prodDetail.collectionSuccess'),
              type: 'success',
              duration: 1000
            })
          } else {
            this.$message({
              message: this.$t('prodDetail.uncollected'),
              duration: 1000
            })
          }
          this.getUserCollection()
        })
    },
    /**
     * 去到首页
     */
    homePage(){
      if(this.shopId){
        window.location.href = `/shopIndex?sid=${this.shopId}`
      }else {
        this.$message({
            type: 'warning',
            message:this.$t('userCenter.theStoreOffline')
        })
      }
    },
    /**
     * 查询该分类下的商品
     */
    getProdListByCategory(categoryId) {
      console.log(this.shopId)
      if(this.shopId){
        if (!categoryId) {
          window.location.href = `/shopIndex?sid=${this.shopId}`
        } else {
          window.location.href = `/shopIndex?sid=${this.shopId}&cid=${categoryId}`
        }
      }else {
        this.$message({
            type: 'warning',
            message:this.$t('userCenter.theStoreOffline')
        })
      }

    },
    /**
     * 搜索商品/查询指定分页下的商品
     */
    getSearchProdPage(current) {
      let prodName = this.prodName ? this.prodName.trim() : ''
      var url = '/shopIndex?sid=' + this.shopId + '&c=' + current
      //通过商品名称搜索
      if (prodName) {
        url = url + '&pn=' + prodName
      }
      //在分类查询的基础上查询/分页
      if (this.categoryId) {
        url = url + '&cid=' + this.categoryId
      }
      window.location.href = url
    },
    /**
     * 轮播图跳转到商品
     */
    imgToProd(banner) {
      if(banner.type !== 0) {
        return
      }
      let prodId = banner.relation
      this.$axios
        .get('/prod/isStatus', {
          params: {
            prodId: prodId
          }
        })
        .then(({ data }) => {
          if (data) {
            this.toProdDetail(prodId)
          }
        })
    },
    /**
     * 跳转到商品
     */
    toProdDetail(prodId) {
      if (prodId) {
        const newPage = this.$router.resolve({ path: '/detail/' + prodId })
        window.open(newPage.href, '_blank')
      }
    },
    /**
     * 价格处理
     */
    parsePrice: value => {
      var val = Number(value)
      if (!val) {
        val = 0
      }
      // 截取小数点后两位，并以小数点为切割点将val转化为数组
      return val.toFixed(2).split('.')
    }


  },

  // 监听id，要是发生变化就重新请求数据
  watch: {
    $route:(to, from)=>{
      // //要处理的操作
      // // console.log(this.queryId)
      // // let routeId = this.$route.query.sid
      // this.getShop(to.query.sid)
      // console.log(to.query.sid)
      // 路由变话页面刷新
      if(to.query.sid===from.query.sid) return
      location.reload()
    }
  }
}
</script>

<style scoped src='~/assets/css/shop-index.css'></style>
<style scoped>
.el-pagination {
  text-align: right;
  padding: 0 30px;
  padding-top: 20px;
}
.pagination .el-pagination button,
.el-pagination span:not([class*='suffix']) {
  padding: 0 8px !important;
}
.pagination .el-pagination.is-background .btn-next,
.el-pagination.is-background .btn-prev,
.el-pagination.is-background .el-pager li {
  background-color: #fff !important;
}
.pagination .el-pagination__editor.el-input .el-input__inner {
  width: 30px !important;
}

.empty .action .btn-r {
  display: inline-block;
  padding: 6px 18px;
  border: 1px solid #ddd;
  background: #f9f9f9;
  border-radius: 30px;
  margin-top: 20px;
  margin-left: 10px;
  color: #666;
}

.empty .action .btn-r:hover {
  background: #fff;
}
.goods-list .list-con .item .goods-msg .goods-name{
  height: 18px;
}
</style>
